package MapJoin;


import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 学习点1：两个表join
 * 学习点2：小表加缓存
 * 学习点3：setup方法的使用
 */
public class DistributedCacheMapper extends Mapper<LongWritable, Text, Text, NullWritable> {

    Map<String, String> pdMap = new HashMap<>();

    //ctrl + o 选中两个方法

    /**
     * 初始化方法
     * 把pd.txt加载进来
     *
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        //把pd.txt文件加载进来
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                new FileInputStream(new File("F:\\date\\A\\mapjoin\\pd.txt")), "UTF-8"));

        String line;
        //import org.apache.commons.lang.StringUtils; 导包注意，是common包，不是hadoop的
        while (StringUtils.isNotEmpty(line = reader.readLine())) {
            String[] fields = line.split("\t");
            //产品id
            String pid = fields[0];
            //产品名字
            String pname = fields[1];
            pdMap.put(pid, pname);
        }
        reader.close();
    }

    Text k = new Text();

    /**
     * order.txt的处理
     *
     * @param key
     * @param value
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void map(LongWritable key,
                       Text value,
                       Context context) throws IOException, InterruptedException {
        //转类型
        String line = value.toString();
        //切分
        String[] fields = line.split("\t");

        //订单id,产品id，产品数量
        String orderId = fields[0];
        String pid = fields[1];
        String amount = fields[2];

        //通过pid（key），拿到pname（value）
        String pname = pdMap.get(pid);

        //数据字段拼接
        k.set(orderId + "\t" + pname + "\t" + amount);

        context.write(k,NullWritable.get());
    }
}
